package cn.nawang.ebeim.ui.controller;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.nawang.ebeim.client.bean.DownloadProcessBarBean;
import cn.nawang.ebeim.client.bean.StorageServer;
import cn.nawang.ebeim.client.bean.UpDownloadFailedBean;
import cn.nawang.ebeim.client.bean.UploadProcessBarBean;
import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.DbUpDownloadFailedUtil;
import cn.nawang.ebeim.client.util.DbUpDownloadUtil;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.util.FileUtil;
import cn.nawang.ebeim.client.util.ZookeeperUtil;
import cn.nawang.ebeim.common.entity.FileInfo;
import cn.nawang.ebeim.ui.bean.User;

/**
 * @ClassName: ProcessBarController
 * @Description: TODO
 * @author fanyb
 * @date Nov 12, 2015 5:50:54 PM
 * @version v1.0
 */
@RestController
public class ProcessBarController {
  private static final Logger LOG = LoggerFactory.getLogger(ProcessBarController.class);

  
  @Autowired
  private HttpSession session;
  /**
   * @author zhangjf
   * @Description: 获取上传进度条
   * @param @param dsIds
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:54:33
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "upload/process/bar", method = RequestMethod.POST)
  public String getUploadProcessBar(String dsIds) {
    LOG.debug("upload/process/bar {}",dsIds);
    String[] arr = dsIds.split(",");
    List<String> idList = new ArrayList<String>();
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      List<UploadProcessBarBean> beans =
          DbUpDownloadUtil.getUploadProcessBars(dsIds, DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING);
//      for (int i = 0; i < beans.size(); i++) {
//        UploadProcessBarBean bean = beans.get(i);
//        if (bean.getCount() >= bean.getTotal()) {
//          DbUpDownloadUtil.updateUploadProcessBarStatus(bean.getDsId(),
//              DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
//        }
//      }
      if (beans.size() == 0) {
        beans = DbUpDownloadUtil.getUploadProcessBars(dsIds,
            DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
      } else {
        for (int i = 0; i < arr.length; i++) {
          boolean exist = false;
          for (UploadProcessBarBean bean : beans) {
            if (arr[i].equals(bean.getDsId())) {
              exist = true;
              break;
            }
          }
          if (!exist) {
            idList.add(arr[i]);
          }
        }
        for (int j = 0; j < idList.size(); j++) {
          UploadProcessBarBean barBean = DbUpDownloadUtil.getUploadProcessBar(idList.get(j),
              DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
          if (barBean != null) {
            beans.add(barBean);
          }
        }
      }

      json.put("code", "200");
      json.put("beans", beans);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "upload/process/bar/all", method = RequestMethod.POST)
  public String getUploadProcessBarAll() {
    User user = (User) session.getAttribute("user");
    String userID = user.getId();
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      List<UploadProcessBarBean> beans = DbUpDownloadUtil.getUploadProcessBarAll(Constants.DS_TYPE_SAFEBOX,userID);
      json.put("code", "200");
      json.put("beans", beans);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  /**
   * @author zhangjf
   * @Description: 删除上传进度条
   * @param @param dsIds
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:55:36
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "upload/process/bar/delete", method = RequestMethod.POST)
  public String deleteUploadProcessBar(String dsIds) {
    LOG.debug("upload/process/bar/delete"+dsIds);
    JSONObject json = new JSONObject();
    json.put("code", "404");
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      String[] arr = dsIds.split(",");
      for (String dsid : arr) {
        UploadProcessBarBean bean =
            DbUpDownloadUtil.getUploadProcessBar(dsid, DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
        if (bean != null) {
          DbUpDownloadUtil.deleteUploadProcessBar(dsid);
          System.out.println(bean);
          json.put("code", "200");
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  /**
   * @author zhangjf
   * @Description: 删除下载进度条
   * @param @param dsId
   * @param @return
   * @return String
   * @date 2015年10月29日上午8:54:24
   *
   * @修改人 zhangjf
   * @修改日期
   */
  @RequestMapping(value = "download/process/bar/delete", method = RequestMethod.POST)
  public String deleteDownloadProcessBar(String nids) {
    LOG.debug("download/process/bar/delete"+nids);
    JSONObject json = new JSONObject();
    json.put("code", "404");
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      String[] arr = nids.split(",");
      for (String nid : arr) {
        DownloadProcessBarBean bean = DbUpDownloadUtil
            .getDownloadProcessBarByNid(DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS, nid);
        if (bean != null) {
          DbUpDownloadUtil.deleteDownloadProcessBarByNid(nid);
          System.out.println(bean);
          json.put("code", "200");
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "download/process/bar/delete/nid", method = RequestMethod.GET)
  public String deleteDownloadProcessBarByNid(String nid) {
    LOG.debug("download/process/bar/delete/nid"+nid);
    JSONObject json = new JSONObject();
    json.put("code", "404");
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      DbUpDownloadUtil.deleteDownloadProcessBarByNid(nid);
      json.put("code", "200");
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "downlaod/process/bar", method = RequestMethod.GET)
  public String getDownloadProcessBars(String nids) {
    LOG.debug("downlaod/process/bar {}",nids);
    String[] arr = nids.split(",");
    List<String> idList = new ArrayList<String>();
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadUtil.initConnection();
      DbUpDownloadUtil.initDatabase();
      List<DownloadProcessBarBean> beans = DbUpDownloadUtil.getDownloadProcessBars(nids,
          DbUpDownloadUtil.PROCESS_BAR_STATUS_RUNNING);
      if (beans.size() == 0) {
        beans = DbUpDownloadUtil.getDownloadProcessBars(nids,
            DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS);
      } else {
        for (int i = 0; i < arr.length; i++) {
          boolean exist = false;
          for (DownloadProcessBarBean bean : beans) {
            if (arr[i].equals(bean.getDsId())) {
              exist = true;
              break;
            }
          }
          if (!exist) {
            idList.add(arr[i]);
          }
        }
        for (int j = 0; j < idList.size(); j++) {
          DownloadProcessBarBean barBean = DbUpDownloadUtil.getDownloadProcessBarByNid(
              DbUpDownloadUtil.PROCESS_BAR_STATUS_SUCCESS, idList.get(j));
          if (barBean != null) {
            beans.add(barBean);
          }
        }
      }

      json.put("code", "200");
      json.put("beans", beans);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "updownload/failed/files", method = RequestMethod.GET)
  public String getUpDownloadFileFaileds(String type) {
    User user = (User) session.getAttribute("user");
    String userID = user.getId();
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadFailedUtil.initConnection();
      DbUpDownloadFailedUtil.initDatabase();
      DbUpDownloadFailedUtil.deleteByStatus(DbUpDownloadFailedUtil.STATUS_FINISHED);
      List<UpDownloadFailedBean> beans = DbUpDownloadFailedUtil.getUpDownloadFaileds(Integer.valueOf(type), Integer.valueOf(userID));
      json.put("code", "200");
      json.put("beans", beans);
    } catch (SQLException e) {
      json.put("code", "500");
      json.put("msg", "sqlite404");
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "updownload/failed/files/tryagain", method = RequestMethod.GET)
  public String upDownloadFileFailedsTryagain(String ids,String type) {
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadFailedUtil.initConnection();
      DbUpDownloadFailedUtil.initDatabase();
      DbUpDownloadFailedUtil.updateNotRunningStatusByIds(DbUpDownloadFailedUtil.STATUS_RUNNING, ids);
      json.put("code", "200");
      json.put("msg", "已加入队列...");
    } catch (SQLException e) {
      json.put("code", "500");
      json.put("msg", "sqlite404");
      e.printStackTrace();
    }
    return json.toString();
  }
  
  @RequestMapping(value = "updownload/failed/files/delete", method = RequestMethod.GET)
  public String deleteUpDownloadFileFaileds(String ids) {
    JSONObject json = new JSONObject();
    try {
      DbUpDownloadFailedUtil.initConnection();
      DbUpDownloadFailedUtil.initDatabase();
      DbUpDownloadFailedUtil.deleteByIds(ids);
      json.put("code", "200");
      json.put("msg", "操作成功！");
    } catch (SQLException e) {
      json.put("code", "500");
      json.put("msg", "sqlite404");
      e.printStackTrace();
    }
    return json.toString();
  }
  
}
